import json
import sys, os
import subprocess

_default_config = """{
    "gpg_key": false,
    "notify": true
}
"""

class Config:
    def __init__(self):
        self.user_home = os.getenv("HOME")
        self.config_dir = f"{self.user_home}/.config/arcalvus"
        self.config_path = f"{self.config_dir}/arcalvus.json"
        self.storage_dir = f"{self.user_home}/Documents/.arcalvus"
        self.cache_dir = f"{self.user_home}/.cache/arcalvus"
        self.cache_path = f"{self.cache_dir}/cache"

        self.conf = {}

        try:
            self.conf = json.loads( open(self.config_path, "r").read() )
        except FileNotFoundError as error:
            if not os.path.isdir(self.config_dir):
                subprocess.run(["/usr/bin/mkdir", "-p", self.config_dir])

            open(self.config_path, "w").write(_default_config)

            #print(f"Config: Not-found config file, created default config in `{self.config_path}`")

        except json.decoder.JSONDecodeError as error:
            print(f"Config: Incorrect syntax `{error}`", file=sys.stderr)
            sys.exit(1)

        except Exception as error:
            print(f"Config: Unknown error `{error}`.", file=sys.stderr)
            sys.exit(1)

        if not os.path.isdir(self.storage_dir):
            subprocess.run(["/usr/bin/mkdir", "-p", self.storage_dir])
            #print(f"Config: Created dir `{self.storage_dir}`")

        if not os.path.isdir(self.cache_dir):
            subprocess.run(["/usr/bin/mkdir", "-p", self.cache_dir])
            #print("Config: Cache directory created.")

    def set_gpg_key(self, key):
        self.conf["gpg_key"] = str(key)

        key_info = subprocess.run(["/usr/bin/gpg", "-k", str(key)], capture_output=True, text=True)

        if key_info.stderr:
            print(f"Config: Invalid key or not key.")
        else:
            print(f"AboutKey:\n{key_info.stdout}")

            open(self.config_path, "w").write( json.dumps(self.conf, indent=4, sort_keys=True, ensure_ascii=False) )

            print(f"Config: Input `{key}` is writed in config.\n")

    def __getitem__(self, key):
        return self.conf.get(key, None)

    def __str__(self):
        return str(self.conf)

    def __repr__(self):
        return f"config(conf={self.conf})"

config = Config()
